//
//  QRCodeViewController.swift
//  DSWeibo
//
//  Created by J on 16/2/22.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate {

    @IBOutlet weak var textLabel: UILabel!//保存扫描到的结果
    @IBOutlet weak var customTabbar: UITabBar!//底部视图
    
    @IBOutlet weak var scanView: UIImageView!//冲击波视图
    @IBOutlet weak var containerHeightConstraint: NSLayoutConstraint!//扫描容器高度
    @IBOutlet weak var scanLineConstraint: NSLayoutConstraint!////冲击波顶部视图
    override func viewDidLoad() {
        super.viewDidLoad()
        //默认选中第0个
        customTabbar.selectedItem = customTabbar.items![0]
        customTabbar.delegate = self
    }

    //关闭
    
    @IBAction func closeBtnLick(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }

    
    
    //冲击波动画
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        textLabel.adjustsFontSizeToFitWidth = true
        starAnimation()//开始动画
        
        //开始扫描
        starscan()
    }

    
    //扫描二维码
    private func starscan(){
        //1.判断是否能够将输入添加到会话中
        if !session.canAddInput(deviceInput) {
            return
        }
        //2.判断是否能够将输出添加到会话中
        if !session.canAddOutput(outPut){
            return
        }
        
        //3.将输入和输出都添加到会话中
        print(outPut.metadataObjectTypes)//能够解析的类型

        session.addInput(deviceInput)
        session.addOutput(outPut)

        //4.设置输出能够解析的数据类型
        //注意:设置解析类型一定要在添加会话之后 否则会报错
        outPut.metadataObjectTypes = outPut.availableMetadataObjectTypes//能解析的都支持
        
        //5.设置输出对象代理 只要解析成功就会通知代理
        outPut.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue() )
        
        //如果想实现只扫描一张图片 那么系统自带的不支持 只能让二维码只有出现在某一块区域才去扫描
//        outPut.rectOfInterest = CGRectMake(0.0, 0.0, 1, 1)
        //添加预览涂层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        //添加绘制图层到预览图层
        previewLayer.addSublayer(drawLayer)
        //6.告诉session开始扫描
        session.startRunning()
        
        
        
    }
    //执行动画
    private func starAnimation(){
        
        //让约束从顶部开始
        self.scanLineConstraint.constant = -self.containerHeightConstraint.constant;
        self.scanView.layoutIfNeeded()
        
        
        //执行冲击波动画
        UIView.animateWithDuration(2.0) { () -> Void in
            //1.修改约束
            self.scanLineConstraint.constant = self.containerHeightConstraint.constant;
            //设置动画执行次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            //2.强直更新界面
            self.scanView.layoutIfNeeded()
        }

    }
    
    //MARK:UITabBarDelegate
    
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        //1.修改容器高度
        
        
        if item.tag == 1 {
          self.containerHeightConstraint.constant = 300
            
        }else{
            
            self.containerHeightConstraint.constant = 150
 
        }
        
        //2.停止动画
        self.scanView.layer .removeAllAnimations()
        
        //3.重新开始动画 用新的containerHeightConstraint 来开始动画 改变冲击波的启示位置
        starAnimation()

    }
    
    
    //MARK:懒加载
    //会话
    private lazy var session : AVCaptureSession = AVCaptureSession()
    
    //拿到输入设备
    private lazy var deviceInput : AVCaptureDeviceInput? = {
        //获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do{
            //创建输入对象
            let input = try AVCaptureDeviceInput(device: device)
            return input

        }catch{
            
            print(error)
            return nil
        }

    }()
    
    //拿到输出对象
    private lazy var outPut :AVCaptureMetadataOutput = AVCaptureMetadataOutput()
        
    //创建二维码预览图层
    private lazy  var previewLayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    
    
    //创建用于绘制边线的涂层
    private lazy var drawLayer: CALayer = {
        let layer = CALayer()
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    


}

extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    
    //只要解析到数据就会调用
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
        //1.获取扫描到的数据
        //2.获取扫描到的二维码位置
//        print(metadataObjects.last)
        //2.1转换坐标
        for object in metadataObjects{
            //2.1.1判断当前获取到的数据,是否是机器可识别的类型
            if object is  AVMetadataMachineReadableCodeObject{
                //2.1.2 将坐标系转换为界面可识别的坐标
               let codeObject =   previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                
//                print(codeObject)
                drcoreners(codeObject)
                
            }
            
        }

        //注意要使用stringValue
//        print(metadataObjects.last?.stringValue)
        textLabel.text = metadataObjects.last?.stringValue
        
        
    
    }
    
    
    //绘制图形 drcoreners 保存了坐标对象
//    Optional(<AVMetadataMachineReadableCodeObject: 0x145439a0, type="org.iso.QRCode", bounds={ 0.2,0.1 0.5x0.9 }>corners { 0.2,1.0 0.7,0.9 0.7,0.1 0.2,0.1 }, time 50456100563666, stringValue "http://plinks.me/t9fxdk")

    private func drcoreners(codeObject:AVMetadataMachineReadableCodeObject){
        //清空图层
        clearCorners()
        //创建一个图层
        if codeObject.corners.isEmpty {
            return//如果为空
        }
        let layer = CAShapeLayer()//CAShapeLayer专门绘图的涂层
        layer.lineWidth   = 4
        layer.fillColor   = UIColor.clearColor().CGColor//背景色
        layer.strokeColor = UIColor.greenColor().CGColor
        
        //创建路径
//        layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).CGPath
        
        let path = UIBezierPath()
        var point = CGPointZero
        var index :Int = 0
        //corners数组中取出第0个元素 将这个字典中x,y赋值给point index++ 先取 index 0
        CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)
        
        path.moveToPoint(point)//移动到0个点
        while index < codeObject.corners.count{//绘制剩下的点
            
            CGPointMakeWithDictionaryRepresentation((codeObject.corners[index++] as! CFDictionaryRef), &point)

            path .addLineToPoint(point)
        }
        
        //2.3关闭路径
        path.closePath()
        
        //2.4绘制路径
        layer.path = path.CGPath
        //2.1将移动到第一个点
//        print(codeObject.corners.last)

        //将绘制好的涂层添加到drawLayer
        drawLayer.addSublayer(layer)
        
    }
    
    //清空上一次的图形
    private func clearCorners(){
        //1.判断drawLayer是否有其他涂层
        
        if drawLayer.sublayers?.count==0 || drawLayer.sublayers==nil{
            return
        }
        
        //2.移除所有 子涂层
        for subLayer in drawLayer.sublayers!{
            subLayer.removeFromSuperlayer()
        }
        
        
    }
    
    ///监听我的名片按钮点击
    @IBAction func myCardBtnClick(sender: AnyObject) {
        let vc = QRCodeCardViewController()
        navigationController!.pushViewController(vc, animated: true)
        
        
        
    }
}
